//
//  RegisterViewController.m
//  ChatKit-OC
//
//  Created by th on 2017/3/21.
//  Copyright © 2017年 ElonChan. All rights reserved.
//

#import "RegisterViewController.h"
#import "UIAutoScrollView.h"
#import "LCChatKitExample.h"
#import "RegisterChildViewController.h"

@interface RegisterViewController ()<UITextFieldDelegate>

@property (nonatomic, strong) UITextField *phoneTF; //手机号码

@property (nonatomic, strong) UITextField *codeTF;//验证码

@property (nonatomic, strong)  UIButton *getCodeButton;//发送验证码按钮

/** 账号 */
@property (nonatomic, strong) UITextField *accountTF;

@property (nonatomic, strong) UITextField *passwordTF;

@property (nonatomic, strong)  NSTimer *timer;

@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"账号注册";
    
    [self setupRegisterUI];
}

- (void)hideKeyboard {
    
    [self.view endEditing:YES];
}

- (void)setupRegisterUI {
    self.view.backgroundColor = [UIColor colorWithRed:0.91 green:0.93 blue:0.93 alpha:1.00];
    
    float y = AUTO_MATE_HEIGHT(0.0f);
    
    UIAutoScrollView *keyScrollView = [[UIAutoScrollView alloc] initWithFrame:CGRectMake(0, y, kMainWidth, kMainHeight - NavigationBar_HEIGHT - STATUS_BAR_HEIGHT)];
    keyScrollView.backgroundColor = [UIColor whiteColor];
    
    [keyScrollView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)]];
    
    [self.view addSubview:keyScrollView];
    
    UILabel *parentLabel = [[UILabel alloc] initWithFrame:CGRectMake(kSpaceX, kSpaceX, keyScrollView.width_pro, 20)];
    
    parentLabel.text = @"注册账号";
    parentLabel.font = [UIFont systemFontOfSize:14];
    parentLabel.textColor = [UIColor grayColor];
    
    [keyScrollView addSubview:parentLabel];
    
    y += parentLabel.maxY_pro + 5;
    
    _accountTF = [[UITextField alloc] initLeftLabelTypeWithY:y placeholder:@"请输入用户名" leftLabelText:@"用户名"];
    _accountTF.delegate = self;
    _accountTF.returnKeyType = UIReturnKeyDone;
    _accountTF.keyboardType = UIKeyboardTypeDefault;
    _accountTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    [_accountTF addLineViewLeftSpace:kSpaceX rightSpace:kSpaceX positionType:kBottom_Type];
    [keyScrollView addSubview:_accountTF];
    
    y = _accountTF.maxY_pro;
    
    _passwordTF = [[UITextField alloc]initLeftLabelTypeWithY:y placeholder:@"请输入6-18位数字或字母密码" leftLabelText:@"密码"];
    _passwordTF.delegate = self;
    _passwordTF.returnKeyType = UIReturnKeyDone;
    _passwordTF.secureTextEntry = YES;
    _passwordTF.keyboardType = UIKeyboardTypeDefault;
    _passwordTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    [_passwordTF addLineViewLeftSpace:kSpaceX rightSpace:kSpaceX positionType:kBottom_Type];
    
    [keyScrollView addSubview:_passwordTF];
    
    y = _passwordTF.maxY_pro ;
    
    _phoneTF = [[UITextField alloc]initLeftLabelTypeWithY:y placeholder:@"请输入手机号" leftLabelText:@"手机号"];
    _phoneTF.keyboardType = UIKeyboardTypeNumberPad;
    _phoneTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    [_phoneTF addLineViewLeftSpace:kSpaceX rightSpace:kSpaceX positionType:kBottom_Type];
    [keyScrollView addSubview:_phoneTF];
    
    y = _phoneTF.maxY_pro;
    
    _codeTF = [[UITextField alloc]initLeftLabelTypeWithY:y placeholder:nil leftLabelText:@"验证码"];
    _codeTF.keyboardType = UIKeyboardTypeNumberPad;
    [keyScrollView addSubview:_codeTF];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(_codeTF.x_pro, _codeTF.maxY_pro, kMainWidth - _codeTF.x_pro*2, 1)];
    line.backgroundColor = kLineViewColor;
    
    [keyScrollView addSubview:line];
    
    //获取验证码
    _getCodeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_getCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    _getCodeButton.backgroundColor = [UIColor colorWithRed:0.04 green:0.43 blue:0.93 alpha:1.00];
    [_getCodeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _getCodeButton.titleLabel.font = [UIFont systemFontOfSize:15];
    
    float width = AUTO_MATE_WIDTH(100.0f);
    
    float x = kRight(_codeTF)- width - 10.0;
    _getCodeButton.frame = CGRectMake(x, (_phoneTF.height_pro - _phoneTF.height_pro * 0.6) * 0.5 + y, width, _phoneTF.height_pro * 0.6);
    [_getCodeButton addTarget:self action:@selector(getCheckCode) forControlEvents:UIControlEventTouchUpInside];
    [keyScrollView addSubview:_getCodeButton];
    _codeTF.width_pro = _codeTF.width_pro - width - kSpaceX;
    
    
    
    y = _codeTF.maxY_pro + 20;
    
    UIButton *registerBtn = [[UIButton alloc] initWithFrame:CGRectMake(kSpaceX, y, kMainWidth - kSpaceX*2, 35)];
    
    registerBtn.backgroundColor = [UIColor colorWithRed:0.06 green:0.47 blue:0.91 alpha:1.00];
    
    [registerBtn setTitle:@"注册" forState:UIControlStateNormal];
    
    [registerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [registerBtn addTarget:self action:@selector(registerTap) forControlEvents:UIControlEventTouchUpInside];
    
    [keyScrollView addSubview:registerBtn];
    
    [keyScrollView addAutoScrollAbility];
}

#pragma mark - 获取验证码按钮响应
- (void)getCheckCode
{
    BOOL isPhone = [RegExpValidate validateMobile:_phoneTF.text];//正则表达式
    if ([_phoneTF.text isEqualToString:@""] || [_phoneTF.text length] == 0) {
        //手机号码不为空
        [self showMsg:@"手机号码不能为空" type:LCCKMessageNotificationTypeError];
        return;
    } else if (isPhone) {
        [self getCodeSuccess];
        
        //改变按钮背景图片
        [_getCodeButton setBackgroundImage:[UIImage imageNamed:@"btn_qrcode"] forState:0];
        return;
    } else {
        [self showMsg:@"手机号码错误" type:LCCKMessageNotificationTypeError];
        _phoneTF.text = nil;
        return;
    }
    
}
// 倒计时
- (void)cutTimeDown:(NSTimer *)timer {
    _getCodeButton.enabled = NO;
    static int time = 60;
        NSString *title = [NSString stringWithFormat:@"剩下（%ds）",time];
        [_getCodeButton setTitle:title forState:UIControlStateDisabled];
    time--;
    if (time == -1) {
        _getCodeButton.enabled = YES;
        [_getCodeButton setTitle:@"重发验证码" forState:0];
        time = 60;
        [timer invalidate];
        timer = nil;
        _timer = nil;
    }
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_timer invalidate];
    _timer = nil;
}
#pragma mark - 请求验证码
- (void)getCodeSuccess
{
    [self.view endEditing:YES];
    
    MJWeakSelf;
    
    [LCChatKitExample invokeThisMethodAfterLoginSuccessWithClientId:@"qq" success:^{
        
        [AVOSCloud requestSmsCodeWithPhoneNumber:_phoneTF.text callback:^(BOOL succeeded, NSError *error) {
            // 发送失败可以查看 error 里面提供的信息
            
            if (succeeded) {
                [self showMsg:@"验证码发送成功" type:LCCKMessageNotificationTypeSuccess];
                
                weakSelf.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(cutTimeDown:) userInfo:nil repeats:YES];
                
            } else {
                [self showMsg:[error localizedDescription] type:LCCKMessageNotificationTypeError];
            }
            
        }];
        
    } failed:^(NSError *error) {
        
        [self showMsg:[error localizedDescription] type:LCCKMessageNotificationTypeError];
    }];
    
}

- (void)showMsg:(NSString *)msg type:(LCCKMessageNotificationType)type {
    [LCCKUtil showNotificationWithTitle:msg
                               subtitle:nil
                                   type:type];
}

- (void)registerTap {
    
    [self hideKeyboard];
    
    if (_accountTF.text.length == 0) {
        [self showMsg:@"账号不能为空" type:LCCKMessageNotificationTypeError];
        return;
    } else if (![RegExpValidate checkPassword:_passwordTF.text]) {
         [self showMsg:@"密码格式错误" type:LCCKMessageNotificationTypeError];
        return;
    } else if (![RegExpValidate validateMobile:_phoneTF.text] || [_phoneTF.text length] == 0) {
        //手机号码不为空
        [self showMsg:@"手机号码错误" type:LCCKMessageNotificationTypeError];
        return;
    } else if (_codeTF.text.length == 0) {
        [self showMsg:@"请输入验证码" type:LCCKMessageNotificationTypeError];
        return;
    } else {
        
        MJWeakSelf;
        void(^registerBlock)() = ^(){
            [AVOSCloud verifySmsCode:_codeTF.text mobilePhoneNumber:_phoneTF.text callback:^(BOOL succeeded, NSError *error) {
                if(succeeded){
                    //验证成功
                    AVUser *user = [AVUser user];
                    
                    user.username = _accountTF.text;
                    user.password = _passwordTF.text;
                    user.mobilePhoneNumber = _phoneTF.text;
                    
                    [user setObject:@"" forKey:kavatarURL];
                    
                    //开启 LeanCloud 的 IM 服务 相应closeWithCallback关闭IM
                    [LCChatKitExample invokeThisMethodAfterLoginSuccessWithClientId:_accountTF.text success:^{
                        
                        [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
                            if (succeeded) {
                                
//                                RegisterChildViewController *childVC = [RegisterChildViewController new];
//                                
//                                childVC.parentUserName = user.username;
//                                childVC.parentObjectId = user.objectId;
//                                
//                                [self.navigationController pushViewController:childVC animated:YES];
                                
                                [weakSelf.navigationController popViewControllerAnimated:YES];
                                
                                [weakSelf showMsg:@"注册成功" type:LCCKMessageNotificationTypeSuccess];
                                
                            } else {
                                [weakSelf showMsg:[error localizedDescription] type:LCCKMessageNotificationTypeError];
                            }
                        }];
                        
                    } failed:^(NSError *error) {
                        [weakSelf showMsg:[error localizedDescription] type:LCCKMessageNotificationTypeError];
                    }];
                    
                } else {
                    [weakSelf showMsg:[error localizedDescription] type:LCCKMessageNotificationTypeError];
                }
            }];
        };
        
        void(^findPhoneBlock)() = ^(){
            
            AVQuery *query = [AVQuery queryWithClassName:kUser];
            
            [query whereKey:@"mobilePhoneNumber" equalTo:_phoneTF.text];//精确查询
            
            [query findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
                if (!error) {
                    if (objects.count > 0) {
                        [weakSelf showMsg:@"当前手机号码已注册" type:LCCKMessageNotificationTypeError];
                    } else {
                        registerBlock();
                    }
                }
            }];
        };
        
        
        AVQuery *query = [AVQuery queryWithClassName:kUser];
        
        [query whereKey:LCCKProfileKeyName equalTo:_accountTF.text];//精确查询
        
        
        [query findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
            
            if (!error) { //查询成功
                if (objects.count > 0) {
                    //有相同名字的用户
                    [weakSelf showMsg:@"当前用户名已注册" type:LCCKMessageNotificationTypeError];
                } else {
                    
                    findPhoneBlock();
                }
            } else {
                
                [weakSelf showMsg:[error localizedDescription] type:LCCKMessageNotificationTypeError];
            }
        }];
    }
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    
    [self registerTap];
    
    return YES;
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
